﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;

namespace PlaxoSyncWM
{
    public class PlaxoSync
    {
        private readonly Regex splitOnRegX = new Regex(@",", RegexOptions.Compiled);
        private readonly PlaxoLogin pl = new PlaxoLogin();
        private readonly IdDeltas ids;
        private HttpWebRequest req;
        private HttpWebResponse resp = null;
        private StreamReader reader;
        private bool check = false;
        private readonly ArrayList arraylist;
        private readonly string username, password, GUID;
        private readonly string lastAnchor;
        private readonly string nextAnchor;
        private string editsURL, addsURL, deletesURL;
        private readonly string begin, end;

        internal PlaxoSync()
        {
            ids = new IdDeltas();
            arraylist = ids.getMobileContactsFileAsArrayList();
            string[] plaxoDetails = pl.getPlaxoSettings();
            username = string.Format(@"'{0}'", plaxoDetails[0]);
            password = string.Format(@"'{0}'", plaxoDetails[1]);
            GUID = plaxoDetails[2];
            Settings settings = new Settings();
            lastAnchor = settings.GetSetting("lastAnchor");
            nextAnchor = settings.GetSetting("nextAnchor");
            begin = string.Format(
                    @"package=['Header', 'ProtoVer', '1', 'ClientID', {0}, 'AuthMethod', 'Plaxo', 'Identifier', {1}, 'Password', {2},'Client', 'Dev Clientname/1.0', 'OS', 'windows/service pack infinity', 'Platform', 'Outlook/2005']%0a['Sync', 'Target', 'Contacts', 'Source', 'DevLocalContacts','LastAnchor', '{3}', 'NextAnchor', '{4}']%0a",
                    GUID, username, password, lastAnchor, nextAnchor);

            end = string.Format(@"['/Sync']");
        }

        public bool slow(string url)
        {
            ServicePointManager.CertificatePolicy = new CertPolicy();
            byte[] buffer = Encoding.ASCII.GetBytes(url);
            req = (HttpWebRequest) HttpWebRequest.Create("https://testapi.plaxo.com/rest?");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = buffer.Length;
            Stream PostData = req.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    string line;
                    reader = new StreamReader(resp.GetResponseStream());
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] elements = splitOnRegX.Split(line);
                        if (line.Contains("Code"))
                        {
                            if (elements[6].Equals(" '200'"))
                                check = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }

            resp.Close();
            req.Abort();
            return check;
        }


        public string createSlowAddUrl()
        {
            string slowReqB = "";
            foreach (string line in arraylist)
            {
                string[] elements = splitOnRegX.Split(line);
                slowReqB = slowReqB + Url.For(elements[0], elements[1], elements[2], elements[3]);
            }
            string url = begin + slowReqB + end;
            return url;
        }

        public string createEditsOnDeviceUrl()
        {
            editsURL = "";
            OutlookSession os = new OutlookSession();
            ArrayList changedIDs = GetChangedIDs();
            string editsY = "";
            foreach (string id in ((IEnumerable)changedIDs[0]))
            {
                if (id != null)
                {
                    Microsoft.WindowsMobile.PocketOutlook.Contact c =
                        new Microsoft.WindowsMobile.PocketOutlook.Contact(new ItemId(int.Parse(id)));
                    string interim =
                        string.Format(
                            @"['Add', 'Type', 'Contact', 'ItemID', '{0}'], ['Data', 'AIMScreenName','', 'Birthday', '','BusinessEmail', '','BusinessIM', '','BusinessMicroBlog', '','BusinessMobilePhone', '', 'Category', '','Company', '', 'DisplayName', '{1} {2}', 'FamilyName', '{2}','FirstName', '{1}','HomeAddress', '', 'HomeCity', '','HomeCountry', '','HomeFax', '','HomePhone', '', 'HomeState', '','HomeZipCode', '','JobTitle', '','LastName', '{2}', 'MiddleName', '','NameSuffix', '','NameTitle', '','NickName', '','Notes', '', 'PersonalEmail', '', 'PersonalIM', '','PersonalMicroBlog', '','PersonalMobilePhone', '{3}', 'PersonalPhoto', '','PersonalWebPage', '', 'PreferredAddress', '', 'WorkAddress', '', 'WorkCity', '','WorkCountry', '','WorkFax', '', 'WorkPager', '','WorkPhone', '', 'WorkState', '','WorkZipCode', '']%0a",
                            c.ItemId, c.FirstName, c.LastName, c.MobileTelephoneNumber);
                    editsY = editsY + interim;
                }
                editsURL = begin + editsY + end;
            }
            os.Dispose();
            return editsURL;
        }

        public ArrayList GetChangedIDs()
        {
            IdDeltas deltas = new IdDeltas();
            ArrayList changedIDs = new ArrayList();
            changedIDs.Add(deltas.IdEditedContacts());
            return changedIDs;
        }

        public string createAddsOnDeviceURL()
        {
            addsURL = "";
            OutlookSession os = new OutlookSession();
            ArrayList addedIDs = ids.IdNewContactsOnDevice();
            string addsB = "";
            if (addedIDs.Count != 0) {
                foreach (string id in addedIDs)
                {
                    if (id != null)
                    {
                        Microsoft.WindowsMobile.PocketOutlook.Contact c =
                            new Microsoft.WindowsMobile.PocketOutlook.Contact(new ItemId(int.Parse(id)));
                        string interim =
                            string.Format(
                                @"['Add', 'Type', 'Contact', 'ItemID', '{0}'], ['Data', 'AIMScreenName','', 'Birthday', '','BusinessEmail', '','BusinessIM', '','BusinessMicroBlog', '','BusinessMobilePhone', '', 'Category', '','Company', '', 'DisplayName', '{1} {2}', 'FamilyName', '{2}','FirstName', '{1}','HomeAddress', '', 'HomeCity', '','HomeCountry', '','HomeFax', '','HomePhone', '', 'HomeState', '','HomeZipCode', '','JobTitle', '','LastName', '{2}', 'MiddleName', '','NameSuffix', '','NameTitle', '','NickName', '','Notes', '', 'PersonalEmail', '', 'PersonalIM', '','PersonalMicroBlog', '','PersonalMobilePhone', '{3}', 'PersonalPhoto', '','PersonalWebPage', '', 'PreferredAddress', '', 'WorkAddress', '', 'WorkCity', '','WorkCountry', '','WorkFax', '', 'WorkPager', '','WorkPhone', '', 'WorkState', '','WorkZipCode', '']%0a",
                                c.ItemId, c.FirstName, c.LastName, c.MobileTelephoneNumber);
                        addsB = addsB + interim;
                    }
                    addsURL = begin + addsB + end;
                }    
            }
            os.Dispose();
            return addsURL;
        }

        public string createDeletesOnDeviceURL() {
            deletesURL = "";
            OutlookSession os = new OutlookSession();
            ArrayList deletedIDs = ids.IdDeletedContacts();
            string deletes = "";
            if (deletedIDs.Count != 0)
            {
                foreach (string id in (deletedIDs))
                {
                    if (id != null)
                    {
                        //Microsoft.WindowsMobile.PocketOutlook.Contact c = os.Contacts.Items.Restrict("ItemId=" + id);
                        //    new Microsoft.WindowsMobile.PocketOutlook.Contact(new ItemId(int.Parse(id)));
                        string interim =
                            string.Format(
                                @"['Delete', 'Type', 'Contact', 'ItemID', '{0}']%0a",
                                id);
                        deletes = deletes + interim;
                    }
                    deletesURL = begin + deletes + end;
                }
            }
            os.Dispose();
            return deletesURL;
        }
    }
}
